<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    @register="registerModal"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :destroyOnClose="true"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} - {{ descriptor?.name }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #scriptLangSlot="{ model, field }">
        <Tabs v-model:activeKey="model[field]">
          <TabPane key="TBEL" tab="TBEL">
            <CodeEditor v-model:value="model['tbelScript']" :mode="MODE.JS" />
          </TabPane>
          <TabPane key="JS" tab="JavaScript">
            <CodeEditor v-model:value="model['jsScript']" :mode="MODE.JS" />
          </TabPane>
        </Tabs>
      </template>
      <template #tableForm="{ model, field, schema }">
        <TableForm
          v-model="model[field]"
          :is-select="schema?.componentProps?.isSelect"
          :left-title="schema?.componentProps?.leftTitle"
          :right-title="schema?.componentProps?.rightTitle"
          :select-type="schema?.componentProps?.selectType"
          :result-type="schema?.componentProps?.resultType"
        />
      </template>
      <template #upload="{ model, field }">
        <Upload
          v-model="model[field]"
          @change="(file:any, fileName:string) => handleChange(field, file, fileName)"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup name="RuleChainNodeDataForm">
  import { Tabs, TabPane } from 'ant-design-vue';
  import { CodeEditor, MODE } from '/@/components/CodeEditor';
  import { ref, unref, computed } from 'vue';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { ComponentDescriptor } from '/@/api/thingsborad/componentDescriptor';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { getSchemas } from './nodeForm.data';
  import { omit } from 'lodash-es';
  import TableForm from './tableForm.vue';
  import Upload from './Upload.vue';

  const emit = defineEmits(['success', 'cancel', 'register']);
  const { meta } = unref(router.currentRoute);

  const [registerForm, { setProps, validate, setFieldsValue, getFieldsValue }] = useForm({
    layout: 'vertical',
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  const nodeId = ref('');
  const id = ref<object | null>();
  const descriptor = ref<ComponentDescriptor>();
  const nodeData = ref<Recordable>({});
  const ruleChainId = ref<string>('');
  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: nodeData.value ? '编辑规则节点' : '添加规则节点',
  }));

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true, ...modalStyleSetting });
    setProps({
      schemas: getSchemas(data.descriptor),
    });
    nodeId.value = data.nodeId || '';
    id.value = data?.data?.id;
    ruleChainId.value = data.ruleChainId;
    nodeData.value = data.data || null;
    descriptor.value = data.descriptor;
    if (data.data) {
      setFieldsValue({
        name: data.data.name,
        debugMode: data.data.debugMode,
        description: data.data.additionalInfo.description,
        ...data.data.configuration,
      });
    } else {
      setFieldsValue({
        ...data.descriptor.configurationDescriptor.nodeDefinition.defaultConfiguration,
      });
    }

    setModalProps({ loading: false });
  });

  async function handleSubmit() {
    await validate();
    const data = getFieldsValue();
    console.log(data);
    if (nodeData.value === null) {
      // 新节点
      emit('success', {
        id: id.value,
        nodeId: nodeId.value,
        ruleChainId: ruleChainId.value,
        name: data.name,
        debugMode: data.debugMode,
        singletonMode: false,
        type: descriptor.value?.clazz,
        configuration: { ...omit(data, ['name', 'debugMode', 'description']) },
        additionalInfo: { description: data.description, layoutX: 0, layoutY: 0 },
        configurationVersion: descriptor.value?.configurationVersion || 0,
      });
    } else {
      // 已有节点
      emit('success', {
        ...Object.assign(nodeData.value, {
          name: data.name,
          debugMode: data.debugMode,
          additionalInfo: Object.assign(nodeData.value.additionalInfo, {
            description: data.description,
          }),
          configuration: { ...omit(data, ['name', 'debugMode', 'description']) },
          nodeId: nodeId.value,
        }),
      });
    }
    closeModal();
  }

  function handleCancel() {
    if (!nodeData.value) {
      emit('cancel', { nodeId: nodeId.value });
    }
    closeModal();
  }

  // 文件上传变更
  const handleChange = (field: string, file: any, fileName: string) => {
    let nameField;
    switch (field) {
      case 'credentials.caCert':
        nameField = 'credentials.caCertFileName';
        break;
      case 'credentials.cert':
        nameField = 'credentials.certFileName';
        break;
      case 'credentials.privateKey':
        nameField = 'credentials.privateKeyFileName';
        break;
    }
    setFieldsValue({
      [field]: file,
      [nameField]: fileName,
    });
  };
</script>

<style lang="less" scoped>
  :deep(.ant-col .ant-form-item-label) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
